package com.geline.easyexcel.interfaces;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import com.geline.easyexcel.domain.DictItem;
import com.geline.easyexcel.domain.EasyExcelProperties;
import com.geline.easyexcel.domain.ParentDict;
import com.geline.easyexcel.utils.DynamicSqlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 默认实现类，如果要实现填写下拉框；需要自定义实现
 *
 * @author: mengxin
 * @date: 2024/1/4 17:41
 */
@Slf4j
public class DefaultDropDownHandler implements DropDownHandler {

    private EasyExcelProperties properties;
    private JdbcTemplate jdbcTemplate;
    private Cache<String, Object> cacheMap = CacheUtil.newLRUCache(500, 300 * 1000);

    public DefaultDropDownHandler(EasyExcelProperties properties, JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
        this.properties = properties;
    }

    @Override
    public List<ParentDict> getDataObject(String dictCode, int dictLevel) {
        List<DictItem> list = listDictItemByCode(dictCode);
        Map<String, DictItem> id2nameMap = new HashMap<>();
        list.stream().forEach(row -> {
            id2nameMap.put(row.getId(), row);
        });

        Map<String, List<DictItem>> map = list.stream().collect(Collectors.groupingBy(DictItem::getParentId));
        List<ParentDict> result = new ArrayList<>();
        for(String key : map.keySet()){
            DictItem dictItem = id2nameMap.get(key);
            if(dictItem!=null && dictItem.getLevel()==dictLevel){
                //parentId=0的不存在
                ParentDict parentDict = new ParentDict();
                parentDict.setDictName(dictItem.getName());
                parentDict.setDictCode(dictItem.getCode()+"_"+key);
                List<DictItem> dictItems = map.get(key);
                List<String> collect = dictItems.stream().map(row -> row.getName()).collect(Collectors.toList());
                parentDict.setItemList(collect);
                result.add(parentDict);
            }
        }
        return result;
    }

    private List<DictItem> listDictItemByCode(String dictCode){
        String cacheKey = String.format("DropDownHandler:%s", dictCode);
        List<DictItem> object = (List<DictItem>) cacheMap.get(cacheKey);
        if (object!=null) {
            return object;
        }
        Map<String, Object> example = new HashMap<>();
        example.put("code", dictCode);
        String dynamicSql = this.properties.getDictSelectSql();
        String sql = DynamicSqlUtil.parseSQL(dynamicSql, example);
        List<DictItem> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(DictItem.class));
        cacheMap.put(cacheKey, list);
        return list;
    }
}
